import BlockIcon from '@/components/workflow/block-icon'
import { WorkflowRunningStatus } from '@/components/workflow/types'
import { INPUT_CONSTRAINTS } from '@/pages/workflow/components/InspectData'
import { useWorkFlowStore } from '@/store/workflowStore'
import cn from '@/util/classnames'
import { RiMoreFill, RiPlayLargeLine } from '@remixicon/react'
import { Dropdown, Input, InputRef, MenuProps, Tooltip, message } from 'antd'
import { trim } from 'lodash'
import { cloneElement, memo, useEffect, useRef, useState } from 'react'
import { useCheckLinkStatus } from '../hooks/use-chek-link'
import NodeResult from '../result/node-result'
import { canRunBySingle, checkNodeValidity, isStartOrEnd, noLeftHandle, noRightHandle , noNodeBody} from '../utils'
import { NodeSourceHandle, NodeTargetHandle } from './components/node-handle'
import './style.less'

message.config({
  duration: 2,
  maxCount: 1
})

const NodePanel = ({ id = 'id', data, selected, children }: any) => {
  const {
    verifying,
    running,
    singleRunningInfo,
    disabledEdit,
    deleteNode,
    setFlowVariables,
    updateRunType,
    updateSingleRunningInfo,
    flowVariables,
    clearRunInfo,
    setVerifying,
    setSelectedNode
  } = useWorkFlowStore()
  const { checkLinkStatus } = useCheckLinkStatus()

  const showSelectedBorder = selected
  const panelWidth = 320
  const nodesReadOnly = false
  const [nodeName, setNodeName] = useState(data.title)
  const [nameIsEditing, setNameIsEditing] = useState(false)

  const inputRef = useRef<InputRef>(null)
  const reName = () => {
    if (disabledEdit) {
      message.warning('运行过程中请勿编辑节点')
      return
    }
    console.log('rename')
    setNameIsEditing(true)
    setTimeout(() => {
      inputRef.current?.focus()
    }, 0)
  }
  const delNode = () => {
    if (disabledEdit) {
      message.warning('运行过程中请勿编辑节点')
      return
    }
    console.log('delNode')
    setSelectedNode(null)
    deleteNode(data.id)
  }
  const nameChange = val => {
    console.log('nameChange')
    const title = trim(val) ? trim(val) : nodeData?.title || nodeName
    setNodeName(title)
    setFlowVariables(id, title, { title })
    setNameIsEditing(false)
  }

  /* =data 监听变化 data状态 */
  const [nodeData, setNodeData] = useState({}) as any
  useEffect(() => {
    if (flowVariables && flowVariables[data.id]) {
      setNodeData({
        ...data,
        ...flowVariables[data.id]
      })
    }
  }, [flowVariables])

  const singleNodeRun = () => {
    if (disabledEdit) {
      message.warning('运行过程中请勿编辑节点')
      return
    }
    // if (!checkLinkStatus()) {
    //   return false
    // }
    // setRunID(data.id)
    clearRunInfo()
    setVerifying(true)
    updateRunType('single')
    /* 失败 */
    if (!checkNodeValidity(nodeData, nodeData.node_type)) {
      updateSingleRunningInfo(nodeData.id, WorkflowRunningStatus.Invalid)
      // setFlowVariables(nodeData.id, nodeData.title, { ...nodeData })
      return
    }
    /* 打开运行弹窗runDrwaerHid 填参数 */
    setTimeout(() => {
      setFlowVariables(nodeData.id, nodeData.title, { ...nodeData, runDrwaerHid: 1 })
    }, 0)
  }

  const moreActions: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <div className="flex h-[32px] flex-1 cursor-pointer items-center gap-2 rounded-md py-1" onClick={reName}>
          <span>重命名</span>
        </div>
      )
    },
    {
      key: '2',
      label: (
        <div className="flex h-[32px] flex-1 cursor-pointer items-center gap-2 rounded-md py-1" onClick={delNode}>
          <span>删除</span>
        </div>
      )
    }
  ]

  // 判断singleRunningInfo的key = data.id
  const hasMatchingId = Object.keys(singleRunningInfo).some(key => key === data.id)

  return (
    <div
      className={cn('relative mr-2 h-full bg-[#ffffff]', 'overflow-visible rounded-2xl shadow-lg transition-all')}
      style={(data.type === "iteration" || data.type === "loop") ? {
        minWidth: `${panelWidth}px`,
        width: 'fit-content',
        maxWidth: '100%' // 可以设置一个最大宽度限制
      }: !noNodeBody(data.type)?{minWidth: `${panelWidth}px`,maxWidth: `${panelWidth}px`}:{width:'158px', padding: '5px'}}
    >
      <div
        className={cn(
          'h-full rounded-2xl transition-all',
          showSelectedBorder ? 'workflow-node-container-bordered' : 'workflow-node-container'
        )}
        style={(data.type === "iteration" || data.type === "loop" )? {
          minWidth: `${panelWidth}px`,
          width: '100%'
        }:!noNodeBody(data.type)?{minWidth: `${panelWidth}px`}:{width:'150px'}}
      >
        {<div className={`sticky top-0 z-10 cursor-move ${!noNodeBody(data.type)? 'border-b-[0.5px] border-black/5':''}`}>
          {(verifying || running) && hasMatchingId && (
            <NodeResult nodeId={data.id} runInfo={singleRunningInfo[data.id]} />
          )}
          <div className="nopan flex items-center px-4 pb-1 pt-1">
            {data.type === 'tool' && data.model?.logo ? (
              <img
                className=" border-white/2 mr-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg text-white shadow-md"
                src={data.model?.logo}
                alt=""
              />
            ) : (
              <BlockIcon className="mr-1 shrink-0" type={data.type} size="md" />
            )}

            <div className="leading-0 flex w-[200px] px-2 py-[5px]">
              {nameIsEditing ? (
                <div className="nopan nodrag">
                  <Input
                    ref={inputRef}
                    defaultValue={nodeName}
                    placeholder="请输入"
                    style={{ width: '100%' }}
                    maxLength={INPUT_CONSTRAINTS.NODE_NAME}
                    onBlur={e => nameChange(e.target.value)}
                    draggable="false"
                  />
                </div>
              ) : (
                nodeData.title || nodeName
              )}
            </div>
            <div
              className="flex shrink-0 items-center justify-end text-gray-500"
              style={{
                width: !noNodeBody(data.type)? '80px':'0px',
                marginLeft: 'auto'  // 添加这行确保靠右
              }}
            >
              {canRunBySingle(data.type) && !nodesReadOnly && (
                <Tooltip title="运行此步骤" className="nodrag nopan mr-1">
                  <div
                    className="nopan nodrag mr-1 flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-black/5"
                    onClick={e => {
                      singleNodeRun()
                    }}
                  >
                    <RiPlayLargeLine className="text-text-tertiary h-4 w-4" />
                  </div>
                </Tooltip>
              )}
              {!isStartOrEnd(data.type) && (
                <div
                  onClick={e => e.stopPropagation()}
                  className="nodrag nopan flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-black/5 ml-auto"
                >
                  <Dropdown 
                    menu={{ items: moreActions }} 
                    placement="bottomRight"
                    align={{ offset: [10, 0] }}
                    getPopupContainer={triggerNode => triggerNode.parentNode as HTMLElement}
                  >
                    <RiMoreFill className={`h-4 w-4 text-gray-500`} />
                  </Dropdown>
                </div>
              )}

              {/* {!noClose(data.type) && <div className="mx-3 h-3.5 w-[1px] bg-[#eaecf0]" />}
              {!noClose(data.type) && (
                <div
                  className="nodrag flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-black/5"
                  data-close="1"
                  onClick={() => {
                    deleteNode(data.id)
                  }}
                >
                  <RiCloseLine
                    className="h-4 w-4"
                    data-close="1"
                    onClick={() => {
                      deleteNode(data.id)
                    }}
                  />
                </div>
              )} */}
            </div>
          </div>
          {/* <div className="p-2">
            <DescriptionInput value={data.desc || ''} onChange={handleDescriptionChange} />
          </div> */}
        </div>}

        {!noLeftHandle(data.type) && (
          <NodeTargetHandle
            id={id}
            data={data}
            handleClassName="absolute top-[50%] -left-[4px] -translate-y-[50%]"
            handleId="target"
          />
        )}

        {!noRightHandle(data.type) && (
          <NodeSourceHandle
            id={id}
            data={data}
            handleClassName="top-[50%] -right-[4px] -translate-y-[50%]"
            handleId="source"
          />
        )}
        {!noNodeBody(data.type) && <div className="px-2 py-2">{cloneElement(children, { id, data })}</div>}
      </div>
    </div>
  )
}

export default memo(NodePanel)
